<script setup>
import { ref, reactive, getCurrentInstance, onMounted, onUnmounted, onBeforeUnmount } from "vue"
import $ from 'jquery';
import * as echarts from "echarts";
import axios from 'axios'
import moment from "moment";
import _ from "lodash";
const { proxy } = getCurrentInstance();
import { Vue3SeamlessScroll } from "vue3-seamless-scroll";

import { ElMessage, ElNotification } from 'element-plus'


const dataList = ref([]);
var dataAlarm = {};
const deviceList = ref([]);
var showVideo = ref(true)
var myChart1 = null;
var myChart2 = null;
var myChart3 = null;
var pie_option = {
    tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    grid: {
        left: "0%",
        top: "0%",
        right: "3%",
        bottom: "0%",
        containLabel: false
    },
    series: [{
        name: '占比情况',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        clockwise: false,
        data: [],
        label: {
            color: 'rgba(255,255,255,.6)',
            fontSize: 14,
        },
        labelLine: {
            show: false
        },
        itemStyle: {

            borderWidth: 0,
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
    }],
    color: ['#62c98d', '#2f89cf', '#4cb9cf', '#09b9af'],
};

var day_option = {
    legend: {
        data: ['昨日', '今日'],
        type: 'scroll',
        textStyle: { color: "#fff" },
        top: '0'
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        }
    },
    color: ["#62c98d", "#2f89cf"],
    grid: {
        top: '14%',
        left: '15',
        right: '35',
        bottom: '12%',
        containLabel: true
    },
    xAxis: [{
        type: 'category',
        axisLabel: {
            color: "rgba(255,255,255,.6)"
        },
        axisLine: { lineStyle: { color: 'rgba(255,255,255,.1)' } },
        data: ['01时', '02时', '03时', '04时', '05时', '06时', '07时', '08时', '09时', '10时', '11时', '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时', '00时'],
    }],
    yAxis: [{
        name: '',
        type: 'value',
        axisTick: { show: false },
        splitLine: {
            show: true,
            lineStyle: {
                color: "#2f2a7a"
            }
        },
        axisLabel: {
            color: 'rgba(255,255,255,.6)'
        },
        axisLine: { lineStyle: { color: 'rgba(255,255,255,.1)' } },
    }],
    dataZoom: [{
        show: true,
        height: 12,
        xAxisIndex: [
            0
        ],
        bottom: 5,
        start: 30,
        end: 80,
        handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
        handleSize: '110%',
        handleStyle: {
            color: "#d3dee5",
        },
        borderColor: "rgba(255,255,255,.3)"
    }],
    series: [
        {
            name: '昨日',
            type: 'bar',

            barWidth: '30',
            data: []
        },
        {
            name: '今日',
            type: 'bar',

            barWidth: '30',
            data: []
        }
    ]
};

var month_option = {
    tooltip: {

        trigger: 'axis',
        axisPointer: {
            lineStyle: {
                color: '#57617B'
            }
        },
        formatter: '{b}:<br/>告警数量:{c}'
    },

    grid: {
        left: '0',
        right: '20',
        top: '10',
        bottom: '20',
        containLabel: true
    },
    xAxis: [{
        type: 'category',
        boundaryGap: false,
        axisLabel: {
            show: true,

            color: 'rgba(255,255,255,.6)'

        },
        axisLine: {
            lineStyle: {
                color: 'rgba(255,255,255,.1)'
            }
        },
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    }],
    yAxis: [{
        axisLabel: {
            show: true,
            color: 'rgba(255,255,255,.6)'
        },
        axisLine: {
            lineStyle: {
                color: 'rgba(255,255,255,.1)'
            }
        },
        splitLine: {
            lineStyle: {
                color: 'rgba(255,255,255,.1)'
            }
        }
    }],
    series: [{
        name: '完成率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 5,
        showSymbol: false,
        lineStyle: {
            width: 3
        },
        areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(98, 201, 141, 0.5)'
            }, {
                offset: 1,
                color: 'rgba(98, 201, 141, 0.1)'
            }], false),
            shadowColor: 'rgba(0, 0, 0, 0.1)',
            shadowBlur: 10
        },
        itemStyle: {
            color: '#4cb9cf',
            borderColor: 'rgba(98, 201, 141,0.27)',
            borderWidth: 12
        },
        data: []
    }]
};

function loadVideo() {

    var video = document.getElementById('video-webrtc');
    var url = 'webrtc://172.16.2.33/live/34020000001320000003.flv';
    var player = new JSWebrtc.Player(url, { video: video, autoplay: true, onPlay: (obj) => { console.log("start play") } });
}

var fetchAllId;
var fetchAlarmId;

onMounted(() => {

    loadDeviceList();

    loadAlarmList();

    loadModelList();

    loadDayList();

    loadMonthList();

    setTimeout(loadVideo, 1000)

    $(".loading").fadeOut()

    fetchAlarmId = setInterval(fetchAlarm, 3000)

    fetchAllId = setInterval(fetchAll, 30000)
})

onUnmounted(() => {
    clearInterval(fetchAlarmId)
    clearInterval(fetchAllId)
    console.log("clearInterval fetchAlarmId", fetchAlarmId);
    console.log("clearInterval fetchAllId", fetchAllId);
})

async function fetchAll() {
    loadModelList();
    loadDeviceList();
    loadDayList();
    loadMonthList();
}
var handler=null;
async function fetchAlarm() {
    try {
        var data = {
            pageIndex: 1,
            pageSize: 5,
            classType: null
        };

        var ret = await axios.get('/api/alarm', {
            params: data
        });

        if (ret.data.code === 0) {
            var count = 0;
            var last = null;
            ret.data.data.alarms.forEach((v) => {
                if (!dataAlarm[v.id]) {
                    if (dataList.value.length >= 10) {
                        dataList.value.shift();
                    }
                    dataList.value.push(v);
                    count++;
                    last = v;
                    dataAlarm[v.id] = 1;
                }

            });

            if(handler){
                handler.close();
            }
            
            if (count) {
                handler=ElNotification({
                    title: '新的告警',
                    customClass: 'notification-custom',
                    dangerouslyUseHTMLString: true,
                    message: `<a href="${last.file_path}"  target="_blank"><img style=\"margin-left:25px;\" src=\"${last.file_path}?w=230&h=150\"></img></a><div style=\"margin-left:25px;\">类型:${last.classType}</div><div style=\"margin-left:25px;\">时间:${formartterTime(last.timestamp)}</div>`,
                    position: 'bottom-right',
                })
            }

        }
    } catch (error) {

    }
}

async function loadDeviceList() {
    try {
        var ret = await axios.get('/api/stat/device');
        if (ret.data.code == 0) {
            ret.data.data = _.orderBy(ret.data.data, ['value'], ['desc'])
            deviceList.value.length = 0;
            ret.data.data.forEach((v) => {
                deviceList.value.push(v);
            });

        } else {
            console.error('Failed to fetch data:', ret.data.error);
        }
    } catch (error) {

    }
}

async function loadAlarmList() {
    try {
        var data = {
            pageIndex: 1,
            pageSize: 7,
            classType: null
        };

        var ret = await axios.get('/api/alarm', {
            params: data
        });

        if (ret.data.code === 0) {
            dataList.value.length = 0;
            dataAlarm = {}
            //console.log(ret.data.data);
            ret.data.data.alarms.forEach((v) => {
                dataList.value.push(v);
                dataAlarm[v.id] = 1;
            });

        } else {
            console.error('Failed to fetch data:', ret.data.error);
            // 可以根据实际情况处理错误，比如弹出错误提示或者执行其他操作
        }
    } catch (error) {
        console.error('Error fetching data:', error);
        // 捕获网络请求失败或其他异常情况，并进行处理
    }
}

async function loadModelList() {
    try {
        var ret = await axios.get('/api/stat/model');

        if (ret.data.code === 0) {

            pie_option.series[0].data.length = 0;
            //console.log(ret.data.data);
            ret.data.data.forEach((v) => {
                pie_option.series[0].data.push(v);
            });
        }
        if (!myChart1) {
            myChart1 = echarts.init(document.getElementById('echart1'));
        }
        // 使用刚指定的配置项和数据显示图表。
        myChart1.setOption(pie_option);
        window.addEventListener("resize", function () {
            myChart1.resize();
        });

    } catch (error) {

    }
}

async function loadDayList() {

    try {
        var ret = await axios.get('/api/stat/twoday');

        if (ret.data.code === 0) {

            day_option.series[0].data.length = 0;
            day_option.series[1].data.length = 0;
            //console.log(ret.data.data);

            ret.data.data["0"].forEach((v) => {
                day_option.series[0].data.push(v.value);
            })
            ret.data.data["1"].forEach((v) => {
                day_option.series[1].data.push(v.value);
            })
        }
        if (!myChart2) {
            myChart2 = echarts.init(document.getElementById('echart2'));
        }
        myChart2.setOption(day_option);
        window.addEventListener("resize", function () {
            myChart2.resize();
        });
    } catch (error) {

    }
}

async function loadMonthList() {
    try {

        var ret = await axios.get('/api/stat/month');

        if (ret.data.code === 0) {
            month_option.series[0].data.length = 0;
            ret.data.data.forEach((v) => {
                month_option.series[0].data.push(v.value);
            })
        }

        if (!myChart3) {
            myChart3 = echarts.init(document.getElementById('echart3'));
        }
        myChart3.setOption(month_option);
        window.addEventListener("resize", function () {
            myChart3.resize();
        });

    } catch (error) {

    }
}

function openWindow(url) {
    window.open(url, "_blank");
}

function formartterTime(timestamp) {
    return moment.utc(timestamp).format("YYYY-MM-DD HH:mm:ss")
}

function addItem() {


    var data = {
        "classType": "person",
        "confidence": 0.99,
        "file_path": "http://172.16.2.33:9100/61e772f91861f2863c33e1acf7fa16f7",
        "id": "c226a21f-2f7d-4c3f-8552-0dbfda1a97eb",
        "timestamp": moment()
    }
    dataList.value.unshift(data);
    dataList.value.push();
    //console.log(proxy.$refs.mySeamlessScroll)
    proxy.$refs.mySeamlessScroll.Reset()

    ElNotification({
        title: '新的告警',
        dangerouslyUseHTMLString: true,
        message: `<a href="${data.file_path}" target="_blank"><img  src=\"${data.file_path}?w=230&h=140\"></img></a><div>类型:${data.classType}</div><div>时间:${formartterTime(data.timestamp)}</div>`,
        position: 'bottom-right',
    })

}

</script>

<template>
    <div class="loading">
        <div class="loadbox"> <img src="../assets/loading.gif"> 页面加载中... </div>
    </div>
    <div class="screen-root">

        <div style="overflow: hidden;background:rgba(0,0,40,0) ; position: relative; z-index: 2;">

            <div class="mainbox">
                <ul class="clearfix">
                    <li>
                        <div class="boxall" style="height:350px;">
                            <div class="alltitle">告警比例</div>
                            <div class="navboxall" ref="echart1" id="echart1" style="margin-left: -20px;margin-top:-10px;">

                            </div>
                        </div>
                        <div class="boxall" style="height:360px;">
                            <div class="alltitle">告警设备</div>
                            <div class="navboxall">
                                <table class="table1" width="100%" border="0" cellspacing="0" cellpadding="0">
                                    <tbody>
                                        <tr>
                                            <th>排名</th>
                                            <th>设备名称</th>
                                            <th>告警数量</th>
                                        </tr>
                                        <tr v-for="(item, index) in deviceList" :key="index">
                                            <td><span>{{ index + 1 }}</span></td>
                                            <td>{{ item.name }}</td>
                                            <td>{{ item.value }}<br></td>
                                        </tr>
                                    </tbody>
                                </table>

                            </div>
                        </div>

                    </li>
                    <li>
                        <div class="boxall" style="height:100px">

                            <div class="navboxall">
                                <h1><a href="/#/center" style="color: #f1f1f1">视频AI智能应用平台</a>
                                    <!-- <el-button @click="addItem">add</el-button> 视频AI智能应用平台-->
                                </h1>

                            </div>
                        </div>
                        <div class="boxall" style="height:610px">

                            <div class="navboxall" style="overflow: hidden;height: 100%">
                                <video v-if="showVideo" style="width: 110%; height: 120%; position: relative; top: -11%;"
                                    id="video-webrtc">

                                </video>
                            </div>
                        </div>

                    </li>
                    <li>
                        <div class="boxall" style="height:725px">
                            <div class="alltitle">告警记录</div>

                            <div class="navboxall">
                                <vue3-seamless-scroll ref="mySeamlessScroll" :step="0.4" :list="dataList" direction="down"
                                    :hover="true" :wheel="true" class="scroll">
                                    <div class="item" v-for="(item, index) in dataList" :key="index">
                                        <el-row>
                                            <el-col :span="14">
                                                <el-image :src="item.file_path + '?w=220&h=140'"
                                                    style="margin-left:5px;margin-top:5px;cursor: pointer;"
                                                    @click="openWindow(item.file_path)">
                                                </el-image>
                                            </el-col>
                                            <el-col :span="10">
                                                <div class="alarm-item">设备: 南京研发中心</div>
                                                <div class="alarm-item">类型: {{ item.classType }}</div>
                                                <div class="alarm-item">可信度: {{ item.confidence.toFixed(2) }}</div>
                                                <div class="alarm-item">发生时间:</div>
                                                <div class="alarm-item">{{ formartterTime(item.timestamp) }}</div>
                                            </el-col>
                                        </el-row>
                                    </div>
                                </vue3-seamless-scroll>
                            </div>
                        </div>


                    </li>
                </ul>
                <ul class="clearfix">
                    <li style="width:60%">
                        <div class="boxall" style="height:300px;">
                            <div class="alltitle">告警时间段</div>
                            <div class="navboxall" ref="echart2" id="echart2">

                            </div>
                        </div>
                    </li>
                    <li style="width: 40%">

                        <div class="boxall" style="height:300px">
                            <div class="alltitle">告警统计</div>
                            <div class="navboxall" ref="echart3" id="echart3"></div>
                        </div>
                    </li>

                </ul>

            </div>
        </div>
    </div>
</template>

<style scoped>
.screen-root {
    width: 100%;
    height: 100vh;
    overflow-x: hidden;
    margin: 0;
    padding: 0px;
    font-family: microsoft yahei;
    background: #003bc9;
    background: linear-gradient(to bottom right, #003bc9, #023ac2, #021341);
}



/* CSS Document */
* {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box
}

*,
body {
    padding: 0px;
    margin: 0px;
    color: #222;
    font-family: "微软雅黑";
}

body {
    color: #666;
    font-size: 16px;
}

li {
    list-style-type: none;
}


.clearfix:after,
.clearfix:before {
    display: table;
    content: " "
}

.clearfix:after {
    clear: both
}

.loading {
    position: fixed;
    left: 0;
    top: 0;
    font-size: 16px;
    z-index: 100000000;
    width: 100%;
    height: 100%;
    background: #1a1a1c;
    text-align: center;
}

.loadbox {
    position: absolute;
    width: 160px;
    height: 150px;
    color: rgba(255, 255, 255, .6);
    left: 50%;
    top: 50%;
    margin-top: -100px;
    margin-left: -75px;
}

.loadbox img {
    margin: 10px auto;
    display: block;
    width: 40px;
}



h1 {
    color: #fff;
    text-align: left;
    font-size: 40px;
    line-height: 64px;
    text-align: center;
}


.mainbox {
    padding: 20px 20px 0px 20px;
}

.mainbox>ul {
    margin-left: -.4rem;
    margin-right: -.4rem;
}

.mainbox>ul>li {
    float: left;
    padding: 0 .4rem
}

.mainbox>ul>li {
    width: 24%
}

.mainbox>ul>li:nth-child(2) {
    width: 52%
}

.boxall {
    padding: 15px;
    background: rgba(0, 0, 0, .2);
    position: relative;
    margin-bottom: 15px;
    ;
    z-index: 10;
}

.alltitle {
    font-size: 18px;
    color: #fff;
    position: relative;
    margin-bottom: 10px;
}

.alltitle:before {
    width: 90%;
    height: 1px;
    top: 12px;
    position: absolute;
    content: "";
    border-bottom: dashed #fff 1px;
    right: 0;
    opacity: .2;
}

.alltitle:after {
    width: 8px;
    height: 10px;
    top: 8px;
    position: absolute;
    content: "";
    border-radius: 20px;
    right: 0;
    background: #0c51f9;
}

.navboxall {
    height: calc(100% - 30px);
}

.table1 th {
    border-bottom: 1px solid rgba(255, 255, 255, .2);
    font-size: 16px;
    color: rgba(255, 255, 255, .6);
    font-weight: normal;
    padding: 10px 0 10px 10px;
}

.table1 td {
    font-size: 16px;
    color: rgba(255, 255, 255, .6);
    padding: 15px 0 0 10px;
}

.table1 span {
    width: 24px;
    height: 24px;
    border-radius: 53px;
    display: block;
    background: #878787;
    color: #fff;
    line-height: 24px;
    text-align: center;
}

.table1 tr:nth-child(2) span {
    background: #ed405d
}

.table1 tr:nth-child(3) span {
    background: #f78c44
}

.table1 tr:nth-child(4) span {
    background: #49bcf7
}


.scroll {
    height: 100%;
    width: 100%;
    margin: 2px auto;
    overflow: hidden;
}

.scroll .item {
    /* display: flex; */
    align-items: center;
    /* justify-content: space-between; */
    padding: 3px 3px;
    color: #fff;
    margin-bottom: 15px;
    border-radius: 2px;
    border-color: #10caeb;
    border-style: solid;
    border-width: 1px;

    background: linear-gradient(to left, #10caeb, #10caeb) left top no-repeat,
        linear-gradient(to bottom, #10caeb, #10caeb) left top no-repeat,
        linear-gradient(to left, #10caeb, #10caeb) right top no-repeat,
        linear-gradient(to bottom, #10caeb, #10caeb) right top no-repeat,
        linear-gradient(to left, #10caeb, #10caeb) left bottom no-repeat,
        linear-gradient(to bottom, #10caeb, #10caeb) left bottom no-repeat,
        linear-gradient(to left, #10caeb, #10caeb) right bottom no-repeat,
        linear-gradient(to left, #10caeb, #10caeb) right bottom no-repeat;
    background-size: 1.2px 20px, 20px 1.2px, 1.2px 20px, 20px 1.2px;
}

.alarm-item {
    color: #fff;
    margin: 5px 0;
}


.el-notification {
    background-color: #0c51f9 !important;
}

.notification-custom {
    background-color: #0c51f9 !important;
}
</style>